use hmacsha1::hmac_sha1;

// 静态变量的值在内存中拥有固定的地址, 使用它的值总会访问到同样的数据
static URL: &str = "https://gw.open.1688.com/openapi/";
static APP_KEY: u32 = 111111;
static APP_SECRET: &str = "xxxxxx";
static API: &str = "com.alibaba.account/alibaba.account.basic";

fn hmac_sha1_func(s: String) -> String {
    /*
    官方文档第四步
     */

    let m = hmac_sha1(APP_SECRET.as_ref(), s.as_bytes());

    hex::encode(m)
}

fn merge_str(a: &String, b: &String) -> String {
    /*
    官方文档第三步
     */

    let mut result = String::new();

    result.push_str(a.as_str());
    result.push_str(b.as_str());

    result
}

fn make_param(param: &str) -> String {
    /*
    官方文档第二步, 拼装参数
     */

    let mut param: Vec<String> = param
        .split("&")
        .map(|param| param.replace("=", ""))
        .collect();

    param.sort();

    param.join("").as_str().to_string()
}

fn main() {
    let url_path = format!("param2/1/{}/{}", API, APP_KEY);
    // 请在此处放入 新鲜的access_token
    let sign = "access_token=9d5737af-1fb7-4b42-8bc2-df2efc458f67";

    // 文档第二步
    let param: String = make_param(&sign);

    // 文档第三步
    let merge_str = merge_str(&url_path, &param);

    // 文档第四步
    let s = hmac_sha1_func(merge_str);

    let mut url = String::new();

    url.push_str(URL);
    url.push_str(url_path.as_str());
    url.push_str("?");
    url.push_str(sign);
    url.push_str("&_aop_signature=");
    url.push_str(s.as_str());

    println!("{:?}", url)
}
